package com.booza.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.booza.model.Currency;
import com.booza.model.TimeZone;

/**
 * A hibernate DAO class which supports simple CRUD operations on the time zone table. 
 * No business logic here. Just the interaction with database.
 * 
 * @see ZoneDAO
 */
@Transactional
public class ZoneDAOImpl implements ZoneDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Inserts a new time zone.
	 * 
	 * @param zone
	 *          -row
	 */
	public void create(TimeZone zone)
	{
		Session session = sessionFactory.getCurrentSession();
		session.save(zone);
	}

	/**
	 * Find all time zones.
	 * 
	 * @return Returns a list of time zones available.
	 */
	@SuppressWarnings("unchecked")
	public List<TimeZone> fetchAll()
	{
		return (List<TimeZone>) sessionFactory.getCurrentSession().createCriteria(TimeZone.class).list();
	}

	/**
	 * Updates zone details.
	 * 
	 * @param zone
	 *          -details to be updated
	 */
	public void update(TimeZone zone)
	{
		sessionFactory.getCurrentSession().update(zone);
	}

	/**
	 * Find time zone row by zone ID.
	 * 
	 * @param id
	 *          -id of the zone
	 * @return Return the matching time zone.
	 */
	public TimeZone findZoneById(Integer id)
	{
		return (TimeZone) sessionFactory.getCurrentSession().get(TimeZone.class, id);
	}

	/**
	 * Find currencies available for the application. Uses currency table for this.
	 * 
	 * @return Return list of currencies available.
	 */
	@SuppressWarnings("unchecked")
	public Collection<Currency> findCurrencies()
	{
		return (List<Currency>) sessionFactory.getCurrentSession().createCriteria(Currency.class).list();
	}

	/**
	 * Find currency details by currency code, for example USD.
	 * 
	 * @param code
	 *          -String
	 * @return Return matching currency details.
	 */
	public Currency findCurrencyByCode(String code)
	{
		return (Currency) sessionFactory.getCurrentSession().createCriteria(Currency.class).add(
				Restrictions.eq("currency", code)).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public TimeZone findZoneByGmt(String gmt)
	{
		TimeZone res = null;
		List<TimeZone> l = sessionFactory.getCurrentSession().createCriteria(TimeZone.class).add(
				Restrictions.like("name", gmt)).list();
		if (l != null && l.size() > 0) {
			res = l.get(0);
		}
		return res;
	}
}
